package com.qf.czh.vhr.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.czh.vhr.Service.HrService;
import com.qf.czh.vhr.entity.Hr;
import com.qf.czh.vhr.entity.RespBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.*;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    HrService hrService;
    @Autowired
    MyFilter myFilter;
    @Autowired
    MyDecision myDecision;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(hrService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
//                .antMatchers("/admin/**").hasRole("admin")
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O object) {
                        object.setSecurityMetadataSource(myFilter);
                        object.setAccessDecisionManager(myDecision);
                        return object;
                    }
                })
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .successHandler((req, resp, auth) -> {
                    Hr hr = (Hr) auth.getPrincipal();
                    //将密码置空
                    hr.setPassword(null);
                    RespBean respBean = RespBean.ok("登录成功", hr);
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    out.write(new ObjectMapper().writeValueAsString(respBean));
                })
                .failureHandler((req, resp, e) -> {
                    RespBean respBean = RespBean.error("登录失败");
                    if (e instanceof BadCredentialsException) {
                        respBean.setMsg("用户名或者密码输入错误，登录失败");
                    } else if (e instanceof LockedException) {
                        respBean.setMsg("账户被锁定，登录失败");
                    } else if (e instanceof AccountExpiredException) {
                        respBean.setMsg("账户过期，登录失败");
                    } else if (e instanceof CredentialsExpiredException) {
                        respBean.setMsg("密码过期，登录失败");
                    } else if (e instanceof DisabledException) {
                        respBean.setMsg("账户被禁用，登录失败");
                    }
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    out.write(new ObjectMapper().writeValueAsString(respBean));
                })
                .permitAll()
                .and()
                .csrf().disable()
                .exceptionHandling().authenticationEntryPoint((req, resp, authException) -> {
            //用户没有登录的时候，访问了一个需要登录才能访问的页面，就会进入到这个回调方法中
            //未认证
            resp.setStatus(401);
            resp.setContentType("application/json;charset=utf-8");
            PrintWriter out = resp.getWriter();
            RespBean respBean = RespBean.error("尚未登录，请登录");
            out.write(new ObjectMapper().writeValueAsString(respBean));
        })
                .accessDeniedHandler(new AccessDeniedHandler() {
                    @Override
                    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
                        response.setStatus(403);
                        response.setContentType("application/json ; charset=utf-8");
                        RespBean respBean = RespBean.error("权限不足");
                        response.getWriter().write(new ObjectMapper().writeValueAsString(respBean));
                    }
                })
                .and()
                .logout()
                .invalidateHttpSession(true)
                .clearAuthentication(true)
                .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                        response.setContentType("application/json;charset=utf-8");
                        RespBean respBean = RespBean.ok("注销成功");
                        response.getWriter().write(new ObjectMapper().writeValueAsString(respBean));
                    }
                });
    }


}
